// Description: 描述
package tools

import (
	"encoding/json"
	"errors"
	"net/http"
	"time"

	"github.com/dgrijalva/jwt-go"
	"github.com/dgrijalva/jwt-go/request"
)

func JwtToken(secretKey string, iat, userId int64) (string, error) {
	now := time.Now().Unix()
	claims := make(jwt.MapClaims)

	claims["iat"] = now
	claims["exp"] = now + iat

	claims["userId"] = userId

	token := jwt.New(jwt.SigningMethodHS256)
	token.Claims = claims

	return token.SignedString([]byte(secretKey))
}

func JwtTokenWithData(secretKey string, iat int64, data map[string]interface{}) (string, error) {
	now := time.Now().Unix()
	claims := make(jwt.MapClaims)

	claims["iat"] = now
	claims["exp"] = now + iat

	for key, val := range data {
		claims[key] = val
	}

	token := jwt.New(jwt.SigningMethodHS256)
	token.Claims = claims

	return token.SignedString([]byte(secretKey))
}

func JwtParseToken(r *http.Request, secret string) (*jwt.Token, error) {
	return request.ParseFromRequest(r, request.AuthorizationHeaderExtractor,
		func(token *jwt.Token) (interface{}, error) {
			return []byte(secret), nil
		}, request.WithParser(&jwt.Parser{
			UseJSONNumber: true,
		}))
}

// JwtParseUserId 通过http请求获取token里面的用户id(过期也会获取到，函数不做过期判断)
func JwtParseUserId(r *http.Request, secret string) (userId int64, err error) {
	tok, _ := JwtParseToken(r, secret)
	if tok == nil {
		return 0, errors.New("无效的token")
	}

	claims, ok := tok.Claims.(jwt.MapClaims)
	if !ok {
		return
	}

	v, ok := claims["userId"]
	if !ok {
		return 0, errors.New("无效的token")
	}

	return v.(json.Number).Int64()
}
